var $content;
var targetID;
var targetDistance;
var targetNom;

function loadStations(){
	$content = $(".page-stations div:jqmData(role=content)");
	$content.html("");
	
	$.mobile.showPageLoadingMsg();
	navigator.geolocation.getCurrentPosition(function(position){
		getStationsByCoord(position.coords.latitude, position.coords.longitude, 1000, showStations);
	}, function(){
		console.log('Erreur GPS, init avec ancienne position connue');
		if(lastPosition!=null){
			getStationsByCoord(lastPosition.coords.latitude, lastPosition.coords.longitude, 1000, showStations);
		}
	},{timeout:5000});
	

}

function showStations(data){
	var html = '<ul id="stations" data-role="listview" data-filter-placeholder="Rechercher une station ..." data-filter="true" data-icon="arrow-r" data-iconpos="right">';

	$.each(data.markers, function(index, elem) {
		//console.log(elem);
		html += '<li> <a href="#" id="'+elem.numStation+'"><h2>'+elem.nomStation+'</h2> <span class="distance">'+Math.round(elem.distance)+' mètres</span> </a> </li>';
	});

	html += '</ul>';

	$content.prepend(html);

	$("#stations").listview();

	addClickEvent();
	$.mobile.hidePageLoadingMsg();
}

function addClickEvent(){
	$("#stations li a").click(function(e){
		e.preventDefault();

		targetID = $(this).attr('id');
		targetDistance = $(this).find('.distance').html();
		targetNom = $(this).find('h2').html();

		$.mobile.changePage( "station.html", {
			data : {
				'id':targetID
			},
			transition : 'fade'
		});
	})
}

$(".page-stations").on("pageshow", function (event) {
	$('.menu').load('menu.html',function(){ $('#menu').panel(); $('#menu').panel('close');});
	loadStations();
});